from flask import Flask, render_template, request, jsonify
import json
import os
import requests

app = Flask(__name__)


# 加载路由配置文件
def load_routes():
    try:
        # 修正配置文件路径为上级目录的config/route.json
        current_dir = os.path.dirname(os.path.abspath(__file__))
        parent_dir = os.path.dirname(current_dir)
        config_path = os.path.join(parent_dir, 'config', 'route.json')

        print(f"尝试加载配置文件: {config_path}")

        with open(config_path, 'r', encoding='utf-8') as file:
            return json.load(file)
    except Exception as e:
        print(f"加载路由配置失败: {e}")
        return []


# 主页路由
@app.route('/')
def index():
    routes = load_routes()
    return render_template('index.html', routes=routes)


# API请求代理
@app.route('/proxy', methods=['POST'])
def proxy():
    data = request.json
    target_url = data.get('url')
    method = data.get('method')
    headers = data.get('headers', {})
    body = data.get('body', {})

    try:
        # 尝试解析JSON请求体
        if body and isinstance(body, str):
            try:
                body = json.loads(body)
            except:
                # 如果不是JSON格式，保持原样
                pass

        # 发送请求
        if method.upper() == 'GET':
            response = requests.get(target_url, headers=headers)
        elif method.upper() == 'POST':
            response = requests.post(target_url, json=body if isinstance(body, dict) else body, headers=headers)
        else:
            return jsonify({'error': f'不支持的HTTP方法: {method}'}), 400

        # 解析响应
        try:
            response_data = response.json()
            is_json = True
        except:
            response_data = response.text
            is_json = False

        return jsonify({
            'status': response.status_code,
            'headers': dict(response.headers),
            'body': response_data,
            'is_json': is_json
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=False)
